<template>
  <div class="operator">
    <el-button type="primary" :icon="useRenderIcon(plus)" @click="add"
      >新增</el-button
    >
    <div class="my-table mt-4">
      <el-table :data="tableData" style="width: 100%" v-loading="listLoading">
        <el-table-column prop="realName" label="名称" width="180" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button
              type="primary"
              size="small"
              :icon="useRenderIcon(edit)"
              @click="editItem(scope.row)"
            />
            <el-button
              type="primary"
              :icon="useRenderIcon(iconDel)"
              size="small"
              @click="del(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="pagi flex flex-row-reverse mt-4">
        <el-pagination
          @current-change="currentChange"
          v-model:page-size="query.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>
    <!-- 添加编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑操作员' : '新建操作员'"
      width="40%"
      @closed="closed"
    >
      <div class="dialog-content">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="姓名" prop="realName">
            <el-input v-model.trim="ruleForm.realName" />
          </el-form-item>
          <el-form-item label="登录名" prop="loginName">
            <el-input v-model.trim="ruleForm.loginName" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.trim="ruleForm.email" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model.trim="ruleForm.mobile" />
          </el-form-item>
          <el-form-item label="登录密码" prop="loginPassword" v-if="!isEdit">
            <el-input
              v-model.trim="ruleForm.loginPassword"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="assignPassword" v-if="!isEdit">
            <el-input
              v-model.trim="ruleForm.assignPassword"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="选择角色" prop="roleKeyList">
            <el-select
              v-model="ruleForm.roleKeyList"
              multiple
              placeholder="Select"
              style="width: 240px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input v-model="ruleForm.note" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit" :loading="isLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import plus from "@iconify-icons/ep/plus";
import iconDel from "@iconify-icons/ep/delete";
import edit from "@iconify-icons/ep/edit";
import { reactive, ref } from "vue";
import {
  getOperatorList,
  getRoleListByOperator,
  editOperator,
  removePermission,
  addOperator,
  operatorLinkRole,
  getAllRole
} from "@/api/system/index";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import type { OperatorResponse } from "@/api/system/system";
import { watch } from "vue";
import { validatePassword, validateEmail, validateMobile } from "./util/index";
import { onMounted } from "vue";
defineOptions({
  name: "operator"
});
interface Form {
  realName: string;
  loginName: string;
  loginPassword: string;
  assignPassword: string;
  mobile: string;
  email: string;
  roleKeyList: string[];
  note: string;
}
onMounted(() => {
  getAllRoleList();
});
// 获取数据
const query = reactive({
  page: 0,
  pageSize: 10
});
const currentChange = (val: number) => {
  query.page = val - 1;
};
const tableData = ref<OperatorResponse[]>([]);
const total = ref(0);
const listLoading = ref(false);
const getAllOperatorList = async () => {
  listLoading.value = true;
  const res = await getOperatorList(query);
  if (res.code === 0) {
    total.value = res.data.total;
    tableData.value = res.data.pageData;
    listLoading.value = false;
  }
};
watch(
  query,
  () => {
    getAllOperatorList();
  },
  {
    deep: true,
    immediate: true
  }
);
const ruleForm = ref<Form>({
  realName: "",
  loginName: "",
  loginPassword: "",
  assignPassword: "",
  mobile: "",
  email: "",
  roleKeyList: [],
  note: ""
});
// 两次密码是否一致
const validateAssignPassword = (rule: any, value: any, callback: any) => {
  if (ruleForm.value.loginPassword !== ruleForm.value.assignPassword) {
    callback(new Error("密码确认和密码不一致"));
  } else {
    callback();
  }
};
// 表单验证规则
const rules = reactive<FormRules<Form>>({
  realName: [{ required: true, message: "请输入名称", trigger: "blur" }],
  loginName: [{ required: true, message: "请输入登录名", trigger: "blur" }],
  loginPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { validator: validatePassword, trigger: "blur" }
  ],
  assignPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      validator: validateAssignPassword,
      trigger: "blur"
    }
  ],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: validateMobile, trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { validator: validateEmail, trigger: "blur" }
  ],
  roleKeyList: [{ required: true, message: "请选择角色", trigger: "blur" }],
  note: [{ required: true, message: "请输入描述", trigger: "blur" }]
});
// 下拉
const options = ref([]);
const getAllRoleList = async () => {
  const res = await getAllRole();
  if (res.code === 0) {
    options.value = res.data.map(el => ({
      value: el.roleId,
      label: el.name
    }));
  }
};
const ruleFormRef = ref<FormInstance>();
// 添加
const add = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};
// 编辑
const operatorId = ref("");
const editItem = async (item: OperatorResponse) => {
  for (const key in ruleForm.value) {
    ruleForm.value[key] = item[key];
  }
  // 获取角色列表
  const res = await getRoleListByOperator(item.operatorId);
  if (res.code === 0) {
    ruleForm.value.roleKeyList = res.data.map(el => el.roleId);
    isEdit.value = true;
    dialogVisible.value = true;
  }
};
// 删除
const del = (item: OperatorResponse) => {
  ElMessageBox.confirm("您确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const res = await removePermission(item.operatorId);
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getAllOperatorList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消"
      });
    });
};
// 弹窗
const dialogVisible = ref(false);
const isEdit = ref(false);
const closed = () => {
  ruleForm.value = {
    realName: "",
    loginName: "",
    loginPassword: "",
    assignPassword: "",
    mobile: "",
    email: "",
    roleKeyList: [],
    note: ""
  };
  ruleFormRef.value.clearValidate();
};
// 添加提交
const addSubmit = async () => {
  const { loginName, loginPassword, realName, mobile, note, roleKeyList } =
    ruleForm.value;
  const res = await addOperator({
    loginName,
    loginPassword,
    realName,
    mobile,
    note
  });
  if (res.code === 0) {
    if (roleKeyList) {
      const newRes = await operatorLinkRole({
        operatorId: res.data,
        roleKeyList
      });
      if (newRes.code === 0) {
        ElMessage.success("添加成功");
      }
    }
  }
};
// 编辑提交
const editSubmit = async () => {
  const { realName, mobile, note, roleKeyList } = ruleForm.value;
  const res = await editOperator({
    operatorId: operatorId.value,
    realName,
    mobile,
    note
  });
  if (res.code === 0) {
    if (roleKeyList) {
      const newRes = await operatorLinkRole({
        operatorId: operatorId.value,
        roleKeyList
      });
      if (newRes.code === 0) {
        ElMessage.success("修改成功");
      }
    }
  }
};
// 提交
const isLoading = ref(false);
const submit = () => {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      isLoading.value = true;
      if (isEdit.value) {
        await editSubmit();
      } else {
        await addSubmit();
      }
      isLoading.value = false;
      dialogVisible.value = false;
      getAllOperatorList();
    }
  });
};
</script>
